/**
 * Created with  SublimeText
 * @Author:      Lyle
 * @DateTime:    2016-12-06 22:23:57
 * @Description: 
 */
import fetch from 'isomorphic-fetch'
import Config from '../../config'
import Lang from '../../i18n/en'
import Util from '../modules/Tools/util'

var dateRefresh = null;

export function login() {
    return (dispatch, getState) => {
        const { loginState } = getState();
        dispatch(requestPosts(loginState));
    }
}

export function handleChange(key, e) {
    return (dispatch, getState) => {
        let value = e.target.value,
            data = {};
        data[key] = value;
        dispatch(resetState(data));
        //console.log('handleChange', getState())
    }
}

export function setIntervalTime() {
    return (dispatch, getState) => {
        dateRefresh = setInterval(function() {
            dispatch({
                type: 'RESET_TIME',
                time: new Date().toString()
            });
        }, 1000);
    }
}

export function clearIntervalTime() {
    clearInterval(dateRefresh);
    dateRefresh = null;
}

function resetState(data) {
    return {
        type: 'RESET_LOGIN',
        data: data
    }
}

function receivePosts(data) {
    let loginState = {};
    if (data.ret == 200) {
        switch (data.data.int) {
            case 0:
                loginState.error = '';
                loginSuccessful();
                break;
            case 1:
                loginState.error = Lang.admin_login_error_1;
                break;
            case 2:
                loginState.error = Lang.admin_login_error_1;
                break;
            default:
        }
    } else {
        loginState.error = data.msg;
    }
    return resetState(loginState);
}

function loginSuccessful() {
    console.log('successful');
    Util.setCookie('client_session_id', new Date().getTime(), { path: '/', domain: Util.rootDomain() });
    window.location.href = '/center';
}

function requestPosts(loginState) {
    let data = {
        username: loginState.username,
        password: loginState.password
    };

    return {
        API: {
            data: data,
            url: Config.API + '?service=AdminUser.login',
            callback: function(dispatch, jsonData) {
                dispatch(receivePosts(jsonData));
            }
        }
    }
}
